import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:gps/gps.dart';
import 'package:device_info/device_info.dart';
import 'package:image_picker/image_picker.dart';
import 'package:connectivity/connectivity.dart';

import 'package:permission_handler/permission_handler.dart';

class WebviewPage extends StatefulWidget {
  @override
  _WebviewPageState createState() => _WebviewPageState();
}

class _WebviewPageState extends State<WebviewPage> {
  final Completer<WebViewController> _controller =
      Completer<WebViewController>();
  WebViewController _webViewController;
  bool isLoading = true;

  //权限判断
  Future<bool> checkPermission() async {
    //检查是否已有读写内存的权限

    PermissionStatus status = await Permission.camera.request();
    PermissionStatus status2 = await Permission.storage.request();
    if (status.isUndetermined) {
      print('未批准权限');
    } else {
      print('已批准-未知是否有权限');
    }

    if (await Permission.storage.request().isGranted) {
      print('有权限');
      return true;
    } else {
      print('无权限');
      return false;
    }
  }

  @override
  Widget build(BuildContext context) {
    String _url = ModalRoute.of(context).settings.arguments;
    checkPermission();
    if (Platform.isAndroid) WebView.platform = SurfaceAndroidWebView();
    return Scaffold(
        body: SafeArea(
      top: true,
      child: Stack(
        children: [
          WebView(
            initialUrl: _url, //'http://112.74.53.82:8082',
            javascriptMode: JavascriptMode.unrestricted,
            onWebViewCreated: (WebViewController webViewController) {
              _controller.complete(webViewController);
              _webViewController = webViewController;
              _webViewController.clearCache(); //清理缓存
            },
            onPageFinished: (finish){
              setState(() {
                isLoading = false;
              });
            },
            javascriptChannels: <JavascriptChannel>[
              _getGPSJavascriptChannel(context),
              _getDeviceInfoJavascriptChannel(context),
              _getImagePickerJavascriptChannel(context),
              _getNetworkJavascriptChannel(context),
            ].toSet(),
          ),
          isLoading?Center(child: CircularProgressIndicator(),):Stack()
        ],
      ),
    ));
  }

  JavascriptChannel _getGPSJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'GPS',
        onMessageReceived: (JavascriptMessage message) async {
          var gps = await Gps.currentGps();
          print(gps);
          _webViewController.evaluateJavascript("callBackGPS('$gps')");
          return gps; //无效
        });
  }

  JavascriptChannel _getDeviceInfoJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'DeviceInfo',
        onMessageReceived: (JavascriptMessage message) async {
          DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
          AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
          Map<String, dynamic> info = {
            "id": androidInfo.id,
            "model": androidInfo.model,
            "version": androidInfo.version.incremental,
          };
          var infoStr = jsonEncode(info); //必须转为字符串输出
          print('获取设备信息（序列化前）：' + info.toString());
          print('获取设备信息（序列化后）：' + infoStr);
          _webViewController.evaluateJavascript("callBackDevice('$infoStr')");
        });
  }

  JavascriptChannel _getImagePickerJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'ImagePicker',
        onMessageReceived: (JavascriptMessage message) async {
          print('获取图片-开始');
          final picker = ImagePicker();
          final pickedFile = await picker.getImage(source: ImageSource.camera);
          print('图片路径：' + pickedFile.path);
          /* 待写图片上传、返回附件id的代码
          if (pickedFile != null) {
            _image = File(pickedFile.path);
          } else {
            print('No image selected.');
          }
           _webViewController.evaluateJavascript("callBackDevice('$infoStr')");
          */
        });
  }

  JavascriptChannel _getNetworkJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'Network',
        onMessageReceived: (JavascriptMessage message) async {
          var connectivityResult = await (Connectivity().checkConnectivity());
          var re = connectivityResult.toString();
          print('网络' + re);
          _webViewController.evaluateJavascript("callBackNetwork('$re')");
          Connectivity()
              .onConnectivityChanged
              .listen((ConnectivityResult result) {
            // Got a new connectivity status!
            print('监听网络' + result.toString());
          });
//          _network();
        });
  }

  _network() {
    print('开始获取网络');
    Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
      print('网络' + result.toString());
      _webViewController.evaluateJavascript("callBackNetwork('$result')");
    });
  }
}
